import React, { useEffect, useRef } from "react";
import Timeline, {
  TimelineGroupBase,
  TimelineItemBase,
} from "react-calendar-timeline";
import "react-calendar-timeline/lib/Timeline.css";
import moment from "moment";
import { APIPagination } from "@/models/common";
import { EventI } from "@/models/events";
import { addZero } from "@/feature/CreateEvent/CreateEvent";
import { patchEventApi } from "@/api/events";
import "moment/locale/ru";

type Props = {
  eventsNormalized: TimelineItemBase<number>[];
  groups: TimelineGroupBase[];
  monthOffset: number;
  data: APIPagination<EventI>;
  setData: (d: APIPagination<EventI>) => void;
};

export const MedScheduler = ({
  data,
  setData,
  eventsNormalized,
  groups,
  monthOffset,
}: Props) => {
  const ref = useRef();
  const minZoomStart = moment().startOf("day").valueOf();
  const minZoomEnd = moment().endOf("day").valueOf();

  const minZoom = minZoomEnd - minZoomStart;

  const maxZoomStart = moment().startOf("month").valueOf();
  const maxZoomEnd = moment().endOf("month").valueOf();

  const maxZoom = maxZoomEnd - maxZoomStart;
  const minTime = moment().add(monthOffset, "month").startOf("month").valueOf();
  const maxTime = moment().add(monthOffset, "month").endOf("month").valueOf();

  useEffect(() => {
    // @ts-ignore
    ref.current.showPeriod(minTime, maxTime);
  }, [monthOffset]);

  const onResize = (
    itemId: number,
    endTimeOrStartTime: number,
    edge: "left" | "right"
  ) => {
    const item = data.results.find((i) => i.id === itemId);
    const itemIndex = data.results.findIndex((i) => i.id === itemId);
    const time = new Date(endTimeOrStartTime);
    const newTime = `${addZero(time.getHours())}:${addZero(
      time.getMinutes()
    )}:${addZero(time.getSeconds())}`;
    const newItem: EventI =
      edge === "left"
        ? {
            ...item,
            start_time: newTime,
          }
        : {
            ...item,
            end_time: newTime,
          };
    patchEventApi(
      itemId,
      edge === "left"
        ? {
            start_time: newTime,
          }
        : {
            end_time: newTime,
          }
    );
    const newArr = [...data.results];
    newArr[itemIndex] = newItem;

    setData({
      ...data,
      results: [...newArr],
    });
  };

  return (
    <>
      <Timeline
        ref={ref}
        groups={groups}
        items={eventsNormalized}
        minZoom={minZoom}
        maxZoom={maxZoom}
        defaultTimeStart={moment().add(-12, "hour")}
        defaultTimeEnd={moment().add(12, "hour")}
        buffer={1}
        onTimeChange={(
          visibleTimeStart,
          visibleTimeEnd,
          updateScrollCanvas
        ) => {
          if (visibleTimeStart < minTime && visibleTimeEnd > maxTime) {
            updateScrollCanvas(minTime, maxTime);
          } else if (visibleTimeStart < minTime) {
            updateScrollCanvas(
              minTime,
              minTime + (visibleTimeEnd - visibleTimeStart)
            );
          } else if (visibleTimeEnd > maxTime) {
            updateScrollCanvas(
              maxTime - (visibleTimeEnd - visibleTimeStart),
              maxTime
            );
          } else {
            updateScrollCanvas(visibleTimeStart, visibleTimeEnd);
          }
        }}
        onItemResize={onResize}
      />
    </>
  );
};
